<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="计算监测量编码">
          <el-input v-model="searchForm.calcCode" placeholder="请输入编码" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="计算监测量名称">
          <el-input v-model="searchForm.calcName" placeholder="请输入名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="启用状态">
          <el-select v-model="searchForm.isEnabled" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card mt-2">
      <el-button type="primary" @click="handleAdd">
        <el-icon>
          <Plus />
        </el-icon>新增计算监测量
      </el-button>
      <el-button type="danger" :disabled="selectedRows.length === 0" @click="handleBatchDelete">
        <el-icon>
          <Delete />
        </el-icon>批量删除
      </el-button>
      <el-table ref="tableRef" v-loading="loading" :data="tableData" @selection-change="handleSelectionChange"
        style="width: 100%" class="mt-2" border>
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column type="index" label="序号" width="60" align="center" fixed="left" />
        <el-table-column prop="calcCode" label="计算监测量编码" align="center"/>
        <el-table-column prop="calcName" label="计算监测量名称" align="center"/>
        <el-table-column prop="unit" label="单位" align="center" width="80" />
        <el-table-column prop="precisionLen" label="小数位数" align="center" />
        <el-table-column prop="exprText" label="公式可读文本" align="center" show-overflow-tooltip />
        <el-table-column label="来源语义" align="center">
          <template #default="{ row }">
            <el-tag :type="getSourceModeTagType(row.sourceMode)">
              {{ getSourceModeLabel(row.sourceMode) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="启用状态" align="center">
          <template #default="{ row }">
            <el-switch v-model="row.isEnabled" :active-value="1" :inactive-value="0"
              @change="handleStatusChange(row)" />
          </template>
        </el-table-column>
        <el-table-column prop="orderNo" label="排序号" align="center" />
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            <el-button size="small" @click="handleViewDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :total="pagination.total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计算监测量编码" prop="calcCode">
              <el-input v-model="formData.calcCode" placeholder="请输入编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计算监测量名称" prop="calcName">
              <el-input v-model="formData.calcName" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="formData.unit" placeholder="请输入单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="小数位数" prop="precisionLen">
              <el-input-number v-model="formData.precisionLen" :min="0" :max="6" controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="来源语义" prop="sourceMode">
              <el-select v-model="formData.sourceMode" placeholder="请选择来源语义" style="width: 100%">
                <el-option label="累计求差" :value="1" />
                <el-option label="瞬时值" :value="2" />
                <el-option label="速率" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序号" prop="orderNo">
              <el-input-number v-model="formData.orderNo" :min="1" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="启用状态" prop="isEnabled">
              <el-radio-group v-model="formData.isEnabled">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 公式项配置 -->
        <el-form-item label="公式项配置">
          <div class="formula-items">
            <div v-for="(item, index) in formData.items" :key="index" class="formula-item">
              <el-row :gutter="20">
                <el-col :span="5">
                  <el-select v-model="item.metricCode" placeholder="选择监测量" style="width: 100%">
                    <el-option v-for="metric in monitoringList" :key="metric.monitorCode"
                      :label="`${metric.monitorName} (${metric.monitorCode})`" :value="metric.monitorCode" />
                  </el-select>
                </el-col>
                <el-col :span="5">
                  <el-select v-model="item.sign" placeholder="符号" style="width: 100%">
                    <el-option label="+" :value="1" />
                    <el-option label="-" :value="-1" />
                  </el-select>
                </el-col>
                <el-col :span="5">
                  <el-input-number v-model="item.coef" placeholder="系数" :precision="6" :step="0.1"
                    controls-position="right" style="width: 100%" />
                </el-col>
                <el-col :span="6">
                  <el-input v-model="item.aliasText" placeholder="展示别名" />
                </el-col>
                <el-col :span="3">
                  <el-button type="danger" link @click="removeFormulaItem(index)"
                    :disabled="formData.items.length <= 1">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </el-button>
                </el-col>
              </el-row>
            </div>
            <el-button type="primary" link @click="addFormulaItem">
              <el-icon>
                <Plus />
              </el-icon>添加公式项
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialog.visible" title="计算监测量详情" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="计算监测量编码">{{ detailData.calcCode }}</el-descriptions-item>
        <el-descriptions-item label="计算监测量名称">{{ detailData.calcName }}</el-descriptions-item>
        <el-descriptions-item label="单位">{{ detailData.unit }}</el-descriptions-item>
        <el-descriptions-item label="小数位数">{{ detailData.precisionLen }}</el-descriptions-item>
        <el-descriptions-item label="来源语义">
          <el-tag :type="getSourceModeTagType(detailData.sourceMode)">
            {{ getSourceModeLabel(detailData.sourceMode) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="启用状态">
          <el-tag :type="detailData.isEnabled === 1 ? 'success' : 'danger'">
            {{ detailData.isEnabled === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="排序号">{{ detailData.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="公式可读文本">{{ detailData.exprText }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailData.remark || '无' }}</el-descriptions-item>
      </el-descriptions>

      <el-divider>公式项详情</el-divider>
      <el-table :data="detailData.items" border>
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="metricCode" label="监测量编码" align="center" />
        <el-table-column prop="aliasText" label="展示别名" align="center" />
        <el-table-column label="符号" align="center" width="80">
          <template #default="{ row }">
            {{ row.sign === 1 ? '+' : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="coef" label="系数" align="center" width="100" />
        <el-table-column prop="orderNo" label="顺序" align="center" width="80" />
      </el-table>

      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Refresh } from '@element-plus/icons-vue'

// API接口
import {
  getMonitoringLibraryList,
  getCalcList,
  getCalcDetail,
  addCalc,
  updateCalc,
  deleteCalc,
  batchDeleteCalc,
  enableCalc,
  sortCalc
} from '@/api/dispatch/affair/calculateSetting'

// 响应式数据
const loading = ref(false)
const tableRef = ref()
const formRef = ref()
const tableData = ref([])
const selectedRows = ref([])
const monitoringList = ref([])

// 搜索表单
const searchForm = reactive({
  calcCode: '',
  calcName: '',
  isEnabled: null
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框控制
const dialog = reactive({
  visible: false,
  title: '新增计算监测量'
})

const detailDialog = reactive({
  visible: false
})

// 表单数据
const formData = reactive({
  id: null,
  calcCode: '',
  calcName: '',
  unit: '',
  precisionLen: 2,
  sourceMode: 1,
  isEnabled: 1,
  orderNo: 1,
  remark: '',
  items: [
    {
      siteId: null,
      pointId: null,
      metricCode: '',
      aliasText: '',
      sign: 1,
      coef: 1,
      orderNo: 1
    }
  ]
})

// 详情数据
const detailData = reactive({
  calcCode: '',
  calcName: '',
  unit: '',
  precisionLen: 2,
  sourceMode: 1,
  isEnabled: 1,
  orderNo: 1,
  remark: '',
  exprText: '',
  items: []
})

// 表单验证规则
const formRules = reactive({
  calcCode: [
    { required: true, message: '请输入计算监测量编码', trigger: 'blur' }
  ],
  calcName: [
    { required: true, message: '请输入计算监测量名称', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ],
  sourceMode: [
    { required: true, message: '请选择来源语义', trigger: 'change' }
  ]
})

// 工具函数
const getSourceModeTagType = (mode) => {
  const types = {
    1: 'success',
    2: 'primary',
    3: 'warning'
  }
  return types[mode] || 'info'
}

const getSourceModeLabel = (mode) => {
  const labels = {
    1: '累计求差',
    2: '瞬时值',
    3: '速率'
  }
  return labels[mode] || '未知'
}

// 初始化加载数据
onMounted(() => {
  loadAllData()
})

// 加载所有数据
const loadAllData = async () => {
  try {
    await Promise.all([
      loadMonitoringList(),
      loadTableData()
    ])
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  }
}

// 加载监测量列表
const loadMonitoringList = async () => {
  try {
    const res = await getMonitoringLibraryList()
    monitoringList.value = res.data || []
  } catch (error) {
    console.error('加载监测量列表失败:', error)
    throw error
  }
}

// 加载表格数据
const loadTableData = async () => {
  try {
    loading.value = true
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm
    }

    const res = await getCalcList(params)
    tableData.value = res.data || []
    pagination.total = res.total || 0
  } catch (error) {
    console.error('加载表格数据失败:', error)
    throw error
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  loadTableData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    calcCode: '',
    calcName: '',
    isEnabled: null
  })
  handleSearch()
}

// 刷新
const handleRefresh = () => {
  loadAllData()
  ElMessage.success('数据刷新成功')
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadTableData()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadTableData()
}

// 选择行变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新增
const handleAdd = () => {
  dialog.title = '新增计算监测量'
  dialog.visible = true
  resetForm()
}

// 编辑
const handleEdit = async (row) => {
  try {
    const res = await getCalcDetail(row.id)
    dialog.title = '编辑计算监测量'
    dialog.visible = true
    Object.assign(formData, res.data)
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

// 查看详情
const handleViewDetail = async (row) => {
  try {
    const res = await getCalcDetail(row.id)
    Object.assign(detailData, res.data)
    detailDialog.visible = true
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定删除计算监测量 "${row.calcName}" 吗？`, '提示', {
      type: 'warning'
    })

    await deleteCalc(row.id)
    ElMessage.success('删除成功')
    await loadTableData()
  } catch {
    // 用户取消删除
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }

  try {
    await ElMessageBox.confirm(`确定删除选中的 ${selectedRows.value.length} 条数据吗？`, '提示', {
      type: 'warning'
    })

    const ids = selectedRows.value.map(item => item.id)
    await batchDeleteCalc({ ids })
    ElMessage.success('删除成功')
    selectedRows.value = []
    await loadTableData()
  } catch {
    // 用户取消删除
  }
}

// 状态切换
const handleStatusChange = async (row) => {
  try {
    const flag = row.isEnabled
    await enableCalc(row.id, flag)
    ElMessage.success('状态更新成功')
  } catch (error) {
    console.error('状态更新失败:', error)
    // 回滚状态
    row.isEnabled = row.isEnabled === 1 ? 0 : 1
    ElMessage.error('状态更新失败')
  }
}

// 添加公式项
const addFormulaItem = () => {
  formData.items.push({
    siteId: null,
    pointId: null,
    metricCode: '',
    aliasText: '',
    sign: 1,
    coef: 1,
    orderNo: formData.items.length + 1
  })
}

// 删除公式项
const removeFormulaItem = (index) => {
  if (formData.items.length > 1) {
    formData.items.splice(index, 1)
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()

    if (formData.id) {
      await updateCalc(formData.id, formData)
      ElMessage.success('修改成功')
    } else {
      await addCalc(formData)
      ElMessage.success('新增成功')
    }

    dialog.visible = false
    await loadTableData()
  } catch (error) {
    if (error && error.fields) {
      // 表单验证失败
      return
    }
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    calcCode: '',
    calcName: '',
    unit: '',
    precisionLen: 2,
    sourceMode: 1,
    isEnabled: 1,
    orderNo: 1,
    remark: '',
    items: [
      {
        siteId: null,
        pointId: null,
        metricCode: '',
        aliasText: '',
        sign: 1,
        coef: 1,
        orderNo: 1
      }
    ]
  })
}
</script>

<style scoped>
.pagination-container {
  display: flex;
  justify-content: flex-end;
}

.formula-items {
  width: 100%;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 16px;
  background-color: #f8f9fa;
}

.formula-item {
  margin-bottom: 16px;
  padding: 12px;
  background: white;
  border-radius: 4px;
  border: 1px solid #e0e0e0;
}

.formula-item:last-child {
  margin-bottom: 0;
}
</style>